package com.dic.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dic.common.constant.ProductConstant;
import com.dic.mall.product.dao.AttrAttrgroupRelationDao;
import com.dic.mall.product.dao.AttrGroupDao;
import com.dic.mall.product.dao.CategoryDao;
import com.dic.mall.product.entity.AttrAttrgroupRelationEntity;
import com.dic.mall.product.entity.AttrGroupEntity;
import com.dic.mall.product.entity.CategoryEntity;
import com.dic.mall.product.service.AttrAttrgroupRelationService;
import com.dic.mall.product.service.CategoryService;
import com.dic.mall.product.vo.AttrRespVo;
import com.dic.mall.product.vo.AttrVo;
import com.google.common.base.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dic.common.utils.PageUtils;
import com.dic.common.utils.Query;

import com.dic.mall.product.dao.AttrDao;
import com.dic.mall.product.entity.AttrEntity;
import com.dic.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //保存属性
        Integer attrType = attr.getAttrType();
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.save(attrEntity);
        //保存关联关系
        if(attr.getAttrType()== ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr,attrAttrgroupRelationEntity);
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }





    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId,String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(attrType)?1:0);
        String key = (String)params.get("key");
        if(catelogId!=0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        if(!Strings.isNullOrEmpty(key)){
            queryWrapper.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> collect = records.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if(categoryEntity!=null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.
                    selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            AttrGroupEntity attrGroupEntity = null;
            if(attrgroupRelationEntity!=null){
                 attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
            }
            if(attrGroupEntity!=null){
                attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);

        return pageUtils;
    }

    @Autowired
    private CategoryService categoryService;

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();

        BeanUtils.copyProperties(attrEntity,attrRespVo);

        //1.设置分组信息
        if(attrEntity.getAttrType()==ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrId));
            if(attrgroupRelationEntity!=null){
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                if(attrGroupEntity!=null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
        }

        //2.设置分类信息,因为在select展示，所以不设置中文名，设置全路径即可
        attrRespVo.setCatelogPath(categoryService.getCategoryPath(attrEntity.getCatelogId()));
        return attrRespVo;
    }


    @Override
    public void updateAttr(AttrRespVo attr) {
        //1.更新属性
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        //2.更新关联
        if(attr.getAttrType()==ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()){
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrgroupRelationEntity.setAttrId(attr.getAttrId());
            attrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer integer = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            if(integer>0){
                attrAttrgroupRelationDao.update(attrgroupRelationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id",attr.getAttrId()));
            }else{
                attrAttrgroupRelationDao.insert(attrgroupRelationEntity);
            }
        }

    }

    @Override
    public List getAttrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrGroupId));
        List<Long> attrIds = relations.stream().map(relationEntity -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds!=null && attrIds.size()>0){
            List<AttrEntity> attrEntities = this.listByIds(attrIds);
            return attrEntities;
        }
        return null;
    }

    @Override
    public void deleteRelation(AttrAttrgroupRelationEntity[] entities) {
        attrAttrgroupRelationDao.deleteBatchRelation(entities);
    }

    @Override
    public PageUtils getNoAttrRelation(Map<String, Object> params, Long attrGroupId) {
        //1.当前分组只能关联自己所属分类里的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2.当前分组只能关联别的分组没有引用的属性
        //2.1当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2.2其他分组关联的属性
        List<Long> collect = group.stream().map(attrGroupEntity1 -> {
            return attrGroupEntity1.getAttrGroupId();
        }).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> relations = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));
        //2.3当前分类中移除其他分组的属性
        List<Long> attrOther = relations.stream().map(relation -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId)
                .eq("attr_type",ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
        if(attrOther!=null && attrOther.size()>0){
            queryWrapper.notIn("attr_id", attrOther);
        }
        String key = (String)params.get("key");
        if(!Strings.isNullOrEmpty(key)){
            queryWrapper.and(obj->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                queryWrapper);

        PageUtils pageUtils = new PageUtils(page);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrsByIds(List<Long> ids) {
        List<Long> list =  baseMapper.selectSearchAttrsByIds(ids);
        return list;
    }
}